import { Button, Form, Input, App, Watermark } from 'antd'
import styles from './index.module.less'
import api from '../../api'
import type { Login } from '../../types/api'
import storage from '../../utils/storage'
import { useEffect, useState } from 'react'
import { useStore } from '../../store'

export default function Login() {
    const getToken = useStore(state => state.getToken)
    const [loading, setLoading] = useState(false)
    const { message } = App.useApp()
    const onFinish = async (values: any) => {
        try {
            setLoading(true)
            const data: any = await api.login(values)

            if (!data) {
                return message.error('登陆失败')
            }
            setLoading(false)
            storage.set('token', data)
            getToken(data)
            message.success('登陆成功')
            const params = new URLSearchParams(location.search)
            setTimeout(() => {
                location.href = params.get('callback') || '/'
            })
        } catch (err) {
            setLoading(false)
            console.log(err);
        }
    }
    const changeTheme = () => {
        const isDark = storage.get('isDark')
        if (isDark) {
            document.documentElement.dataset.theme = 'dark'
            document.documentElement.classList.add('dark')
        } else {
            document.documentElement.dataset.theme = 'light'
            document.documentElement.classList.remove('dark')
        }
    }

    useEffect(() => {
        changeTheme()
    }, [])

    return (
        <Watermark content="login">
            <div className={styles.login}>
                <div className={styles.loginWrapper}>
                    <div className={styles.title}>系统登陆</div>
                    <Form
                        name="basic"
                        initialValues={{ remember: true }}
                        onFinish={onFinish}
                        autoComplete="off"
                    >
                        <Form.Item
                            name="userName"
                            rules={[{ required: true, message: 'Please input your username!' }]}
                        >
                            <Input />
                        </Form.Item>
                        <Form.Item
                            name="userPwd"
                            rules={[{ required: true, message: 'Please input your password!' }]}
                        >
                            <Input.Password />
                        </Form.Item>
                        <Form.Item>
                            <Button type="primary" block htmlType="submit" loading={loading}>
                                登陆
                            </Button>
                        </Form.Item>
                    </Form>
                </div>
            </div>
        </Watermark>
    )
}